import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:top_foundation/utils/theme/button.dart';
import 'package:top_foundation/utils/theme/theme.dart';
import 'package:whale/helper/component/download/state.dart';
import 'package:whale/helper/utils/util.dart';

import 'index.dart';

class DownloadDemoPage extends GetView<DownloadDemoController> {
  const DownloadDemoPage({Key? key}) : super(key: key);

  Widget stateItem(int index, String url, String stateText) {
    return IButton.text(
      onPressed: () {
        controller.download(index, url);
      },
      text: stateText,
    );
  }

  // 主视图
  Widget _buildView() {
    var state = controller.state;
    return ListView.builder(
      itemBuilder: (context, index) {
        var url = state.urls[index];
        var model = state.downList
            .firstWhereOrNull((element) => element.httpUri == url);
        return ListTile(
          title: Text(
            url,
            style: ITheme.text.titleMedium,
          ),
          trailing: model == null
              ? IButton.text(
                  onPressed: () {
                    controller.download(index, url);
                  },
                  text: '下载',
                )
              : Obx(() => IButton.text(
                    onPressed: () {
                      controller.download(index, url);
                    },
                    text: model.stateText.value,
                  )),
        );
      },
      itemCount: state.urls.length,
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<DownloadDemoController>(
      builder: (_) {
        return Scaffold(
          appBar: AppBar(
            title: const Text("download_demo"),
            actions: [
              TextButton(
                  onPressed: () {
                    controller.toDownload();
                  },
                  child: Text('下载管理'))
            ],
          ),
          body: SafeArea(
            child: _buildView(),
          ),
        );
      },
    );
  }
}
